<?php
namespace app\admin\model;

use think\Model;
use think\Db;
use think\Url;

class AuthRuleModel extends Model
{
    // 指定表名,不含前缀
    protected $name = 'auth_rule';
    //主键名
    protected $pk = 'id';

    public function getRuleList()
    {
        return $this::all();
    }

    public function getMenu($group_id = 0)
    {
        $where = ['status' => 1, 'type' => 1];
        if ($group_id) {
            $groupInfo = Db::name('AuthGroup')->field('rules')->where('id', $group_id)->find();
            if ($groupInfo && !empty($groupInfo['rules'])) {
                $rules = explode(',', $groupInfo['rules']);
                $where['id'] = ['in', $rules];
            }
        }
        $res = Db::name('AuthRule')->where($where)->order(['sort' => 'asc'])->select();

        return \PHPTree::makeTree($res);
    }

    /**
     *获取节点数据
     */
    public function getTreeRule($id)
    {
        $result = $this->field('id,title,pid')->select();
        $str = "";
        $role = new AuthGroupModel();
        $re = $role->getRuleById($id)->data;

        if (!empty($re)) {
            $rule = explode(',', $re['rules']);
        }

        foreach ($result as $key => $vo) {
            $str .= '{ "id": "' . $vo['id'] . '", "pId":"' . $vo['pid'] . '", "name":"' . $vo['title'] . '"';

            if (!empty($rule) && in_array($vo['id'], $rule)) {
                $str .= ' ,"checked":1';
            }

            $str .= '},';
        }

        return "[" . substr($str, 0, -1) . "]";
    }

}